package com.ruoyi.merchant.service.impl;

import com.ruoyi.basedata.domain.WalletKind;
import com.ruoyi.basedata.mapper.PayKindMapper;
import com.ruoyi.basedata.mapper.WalletKindMapper;
import com.ruoyi.channel.domain.MpChannel;
import com.ruoyi.channel.domain.MpChannelMethod;
import com.ruoyi.channel.mapper.MpChannelMapper;
import com.ruoyi.channel.mapper.MpChannelMethodMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.GoogleCodeUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.merchant.domain.MpMerchant;
import com.ruoyi.merchant.domain.MpMerchantMethod;
import com.ruoyi.merchant.domain.MpMerchantRSP;
import com.ruoyi.merchant.domain.MpMerchantWallet;
import com.ruoyi.merchant.mapper.MpMerchantMapper;
import com.ruoyi.merchant.mapper.MpMerchantMethodMapper;
import com.ruoyi.merchant.mapper.MpMerchantWalletMapper;
import com.ruoyi.merchant.service.IMpMerchantService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *  服务层实现
 * 
 * @author ruoyi
 * @date 2019-05-06
 */
@Service
public class MpMerchantServiceImpl implements IMpMerchantService 
{
	Logger logger = LoggerFactory.getLogger(MpMerchantServiceImpl.class);

	@Autowired
	private MpMerchantMapper mpMerchantMapper;
	@Autowired
	private MpMerchantMethodMapper merchantMethodMapper;
	@Autowired
	private WalletKindMapper walletKindMapper;
	@Autowired
    private MpMerchantWalletMapper merchantWalletMapper;
	@Autowired
	private MpChannelMethodMapper channelMethodMapper;
	@Autowired
	private MpChannelMapper channelMapper;


	/**
     * 查询信息
     * 
     * @param id ID
     * @return 信息
     */
    @Override
	public MpMerchant selectMpMerchantById(Long id)
	{
	    return mpMerchantMapper.selectMpMerchantById(id);
	}
	
	/**
     * 查询列表
     * 
     * @param mpMerchant 信息
     * @return 集合
     */
	@Override
	public List<MpMerchantRSP> selectMpMerchantList(MpMerchant mpMerchant)
	{
	    return mpMerchantMapper.selectMpMerchantList(mpMerchant);
	}


    /**
     * 新增
     *
     * @param mpMerchant 信息
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
    public AjaxResult insertMpMerchant(MpMerchant mpMerchant, BigDecimal payRate)
    {
        try {
			// 谷歌验证秘钥
			mpMerchant.setGoogleSecret(GoogleCodeUtil.createSecretKey());
			// 一个用户只能添加一个商户
			MpMerchant merchantAdd = new MpMerchant();
			merchantAdd.setUserId(mpMerchant.getUserId());
			List<MpMerchantRSP> merchantRSPList = mpMerchantMapper.selectMpMerchantList(merchantAdd);
			if (merchantRSPList.size() > 0) {
				return AjaxResult.error("已有商户("+ merchantRSPList.get(0).getName()  +")关联所属用户，一个商户只能关联一个用户");
			}

            // 新增商户
            mpMerchantMapper.insertMpMerchant(mpMerchant);


            // 给新增的商户添加所有钱包类型
            MpMerchant merchant = mpMerchantMapper.checkMerchantNameUnique(mpMerchant.getName());
            WalletKind walletKind = new WalletKind();
            List<WalletKind> walletKindList = walletKindMapper.selectWalletKindList(walletKind);
            if (walletKindList.size() > 0) {
                for (WalletKind walletKindAdd : walletKindList) {
                    MpMerchantWallet merchantWallet = new MpMerchantWallet();
                    merchantWallet.setMerchantId(merchant.getId().intValue());
                    merchantWallet.setWalletKindId(walletKindAdd.getId().intValue());
                    merchantWallet.setAccountBalance(new BigDecimal("0.0000"));
                    merchantWallet.setFrozenBalance(new BigDecimal("0.0000"));
                    merchantWallet.setUnliquidatedBalanceOne(new BigDecimal("0.0000"));
                    merchantWallet.setUnliquidatedBalanceTwo(new BigDecimal("0.0000"));
                    merchantWallet.setdZero(new BigDecimal("1.0000"));
                    // 新增商户钱包
                    merchantWalletMapper.insertMpMerchantWallet(merchantWallet);
                }
            }

			// 增的商户添加所有的渠道支付方法
			List<MpMerchantMethod> merchantMethodList = addMerchantMethod(merchant, payRate);
            if (merchantMethodList.size() > 0) {
                merchantMethodMapper.insertMerchantMethodList(merchantMethodList);
            }

			return AjaxResult.success("添加成功！");
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("添加商户异常！请联系管理员!", e);
            return AjaxResult.error("添加商户异常！请联系管理员!");
        }
    }
	/**
     * 修改
     * 
     * @param mpMerchant 信息
     * @return 结果
     */
	@Override
	public AjaxResult updateMpMerchant(MpMerchant mpMerchant)
	{
		// 更新商户支付方法的商户信息
		MpMerchantMethod merchantMethod = new MpMerchantMethod();
		merchantMethod.setMerchantId(mpMerchant.getId());
		List<MpMerchantMethod> merchantMethodList = merchantMethodMapper.selectMpMerchantMethodList(merchantMethod);
		if (merchantMethodList.size() > 0) {
			for (MpMerchantMethod merchantMethodUpdate : merchantMethodList) {
				merchantMethodUpdate.setMerchantName(mpMerchant.getName());
				merchantMethodUpdate.setMerchantCode(mpMerchant.getCode());
				merchantMethodUpdate.setMerchantStatus(mpMerchant.getStatus());
				// 更新商户支付方法
				merchantMethodMapper.updateMpMerchantMethod(merchantMethodUpdate);
			}
		}
		// 一个商户只能关联一个用户
		MpMerchant merchantEdit = new MpMerchant();
		merchantEdit.setUserId(mpMerchant.getUserId());
		List<MpMerchantRSP> merchantRSPList = mpMerchantMapper.selectMpMerchantList(merchantEdit);
		if (merchantRSPList.size() > 0) {
			MpMerchantRSP merchantRSP = merchantRSPList.get(0);
			if (!merchantRSP.getId().equals(mpMerchant.getId())) {
				return AjaxResult.error("已有商户("+ merchantRSP.getName() +")关联所属用户，一个商户只能关联一个用户！");
			}
		}
		mpMerchantMapper.updateMpMerchant(mpMerchant);
		return AjaxResult.success("修改成功！");
	}

	/**
     * 删除对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteMpMerchantByIds(String ids)
	{
		return mpMerchantMapper.deleteMpMerchantByIds(Convert.toStrArray(ids));
	}

	/**
	 * 修改商户信息状态
	 * @param mpMerchant
	 * @return
	 */
	@Override
	public int changeStatus(MpMerchant mpMerchant) {
		// 查询商户支付方法   修改商户的状态字段
		MpMerchantMethod merchantMethod = new MpMerchantMethod();
		merchantMethod.setMerchantId(mpMerchant.getId());
        List<MpMerchantMethod> merchantMethodListExist = merchantMethodMapper.selectMpMerchantMethodList(merchantMethod);
        if (merchantMethodListExist.size() > 0) {
            for (MpMerchantMethod merchantMethodExist : merchantMethodListExist) {
                merchantMethodExist.setMerchantStatus(mpMerchant.getStatus());
                // 更新
                merchantMethodMapper.updateMpMerchantMethod(merchantMethodExist);
            }
        }
        return mpMerchantMapper.updateMpMerchant(mpMerchant);
	}

	/**
	 * 检验商户名称唯一
	 */
	@Override
	public String checkMerchantNameUnique(MpMerchant mpMerchant) {
		Long mpMerchantId = StringUtils.isNull(mpMerchant.getId()) ? -1L : mpMerchant.getId();
		MpMerchant info = mpMerchantMapper.checkMerchantNameUnique(mpMerchant.getName());
		if (StringUtils.isNotNull(info) && info.getId().longValue() != mpMerchantId.longValue()) {
			return "1";
		}
		return "0";
	}


	/**
	 * 新增的商户添加所有的渠道支付方法
	 */
	public List<MpMerchantMethod> addMerchantMethod(MpMerchant merchant, BigDecimal payRate) {
		// 所有的渠道支付方法
		MpChannelMethod channelMethodExist = new MpChannelMethod();
		List<MpChannelMethod> channelMethodExistList = channelMethodMapper.selectMpChannelMethodList(channelMethodExist);


        // 要添加的商户支付方法集合
        List<MpMerchantMethod> merchantMethodList = new ArrayList<>();
		if (channelMethodExistList.size() > 0) {
            for (MpChannelMethod channelMethod : channelMethodExistList) {
                MpMerchantMethod merchantMethod = new MpMerchantMethod();
                // 商户支付方法 - 信息
                merchantMethod.setPayRate(payRate);
                merchantMethod.setLevel(10);
                merchantMethod.setStatus(1);

                // 商户支付方法 - 商户信息
                merchantMethod.setMerchantId(merchant.getId());
                merchantMethod.setMerchantName(merchant.getName());
                merchantMethod.setMerchantCode(merchant.getCode());
                merchantMethod.setMerchantStatus(merchant.getStatus());

                // 商户支付方法  - 渠道支付方法信息
                merchantMethod.setChannelMethodId(channelMethod.getId());
                merchantMethod.setChannelMethodStatus(channelMethod.getStatus());
                merchantMethod.setChannelMethodPayRate(channelMethod.getPayRate());
                merchantMethod.setChannelMethodPayLimitLeft(channelMethod.getPayLimitLeft());
                merchantMethod.setChannelMethodPayLimitRight(channelMethod.getPayLimitRight());

                // 商户支付方法 - 渠道信息
                MpChannel channel = channelMapper.selectMpChannelById(channelMethod.getChannelId().intValue());
                merchantMethod.setChannelId(channel.getId());
                merchantMethod.setChannelName(channel.getName());
                merchantMethod.setChannelCode(channel.getCode());
                merchantMethod.setChannelStatus(channel.getStatus());
                merchantMethod.setChannelWithdrawalLevel(channel.getWithdrawalLevel());
                merchantMethod.setChannelWithdrawalFee(channel.getWithdrawalFee());
                merchantMethod.setChannelMchWithdrawalFee(channel.getMchWithdrawalFee());
                merchantMethod.setChannelWithdrawalLimtLeft(channel.getWithdrawalLimtLeft());
                merchantMethod.setChannelWithdrawalLimtRight(channel.getWithdrawalLimtRight());
                merchantMethod.setChannelClassName(channel.getClassName());
                merchantMethod.setChannelReqUrl(channel.getReqUrl());
                merchantMethod.setChannelSecretKey(channel.getSecretKey());
                merchantMethod.setChannelWithdrawalInner(channel.getWithdrawalInner());

                // 商户支付方法 - 支付类型信息
                merchantMethod.setPayKindId(channelMethod.getPayKindId());
                merchantMethod.setPayKindName(channelMethod.getPayKindName());
                merchantMethod.setPayKindCode(channelMethod.getPayKindCode());

                // 商户支付方法 - 钱包类型信息
                merchantMethod.setWalletKindId(channelMethod.getWalletKindId());
                merchantMethod.setWalletKindName(channelMethod.getWalletKindName());
                merchantMethod.setWalletKindCode(channelMethod.getWalletKindCode());

                merchantMethodList.add(merchantMethod);
            }
        }
        return merchantMethodList;
	}
}
